package userRoleController

import (
	"CMETO/models"
	"fmt"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

type UserRoleController struct{}

// 查询用户的角色信息（一步到位版）
func (ur UserRoleController) QueryUserRole(ctx *gin.Context) {
	// 获取分页参数
	page, _ := strconv.Atoi(ctx.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(ctx.DefaultQuery("pageSize", "10"))
	nameStr := ctx.DefaultQuery("username", "")
	username := "%" + nameStr + "%"
	userList := []models.User{}
	models.DB.Model(&models.User{}).Preload("Role", "is_delete=0").Select("users.id,users.description,users.englishname,users.account,users.phone,users.department,users.email,users.status,users.username,users.gender").Where("is_delete!=1 AND username like ? ", username).Limit(pageSize).Offset(pageSize * (page - 1)).Find(&userList)
	var total int64
	models.DB.Table("users").Where("is_delete!=1 AND username like ?", username).Count(&total)
	result := &models.ResultByPage[models.User]{
		Msg:      "ok",
		Code:     "200",
		Total:    total,
		Page:     page,
		PageSize: pageSize,
		Result:   userList,
	}
	ctx.JSON(http.StatusOK, result)
}

// 根据角色id查用户
func (ur UserRoleController) QueryUserByRole(ctx *gin.Context) {
	// 获取分页参数
	page, _ := strconv.Atoi(ctx.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(ctx.DefaultQuery("pageSize", "10"))
	role, _ := strconv.Atoi(ctx.DefaultQuery("role", "0"))
	var roleStr string
	if role != 0 {
		roleStr = fmt.Sprint("roles.id=", role)
	} else {
		roleStr = "1=1"
	}
	nameStr := ctx.DefaultQuery("username", "")
	usernameStr := "%" + nameStr + "%"
	userList := []models.User{}
	models.DB.Table("users").
		Select("users.id,users.description,users.englishname,users.phone,users.username,users.account,users.status,users.email,users.gender,roles.name").
		Joins("LEFT JOIN user_role ON users.id = user_role.user_id").
		Joins("LEFT JOIN roles ON user_role.role_id = roles.id").
		Where(roleStr+" AND "+"users.username like ? AND users.is_delete =0", usernameStr).
		Scan(&userList)
	var total int64
	models.DB.Table("users").Where("users.is_delete!=1 AND users.username like ?", usernameStr).Joins("LEFT JOIN user_role ON users.id = user_role.user_id").
		Joins("LEFT JOIN roles ON user_role.role_id = roles.id").
		Where(roleStr).Count(&total)
	result := &models.ResultByPage[models.User]{
		Msg:      "ok",
		Code:     "200",
		Total:    total,
		Page:     page,
		PageSize: pageSize,
		Result:   userList,
	}
	ctx.JSON(http.StatusOK, result)
}
